<?php
class Page_worklist extends V_View {
		// ------------------------------------------------------------------------------------------
    	// ----------Главная страница и песочница ---------------------------------------------------
    	// ------------------------------------------------------------------------------------------
        function index () {
        	$this->jobs();
        }
		function all () {
        	$this->assign('page_title','Все рабочие листы');
            $this->display('header.tpl');
            $this->display('pages/worklist/worklist.tpl');
            $this->display('footer.tpl');
        }
		function my () {
        	$this->assign('page_title','Мои рабочие листы');
            $this->display('header.tpl');
            $this->display('pages/worklist/worklist.tpl');
            $this->display('footer.tpl');
        }
		function signed () {
        	$this->assign('page_title','Подписанные листы');
            $this->display('header.tpl');
            $this->display('pages/worklist/worklist.tpl');
            $this->display('footer.tpl');
        }
		function jobs () {
        	$this->assign('page_title','Список заданий');
            $this->display('header.tpl');
            $this->display('pages/worklist/jobs.tpl');
            $this->display('footer.tpl');
        }
        // ------------------------------------------------------------------------------------------
    	// ----------Добавление рабочего листа-------------------------------------------------------
    	// ------------------------------------------------------------------------------------------
		function listadd () {
            // Если форма отправлена - проверка данных
            if (isset ($_POST['action']) and $_POST['action']=='add') {
                $state="OK";
                $company=V_DB::escape($_POST['cname']);
                $phone=V_DB::escape($_POST['cphone']);
                $date=V_DB::escape($_POST['cdate']);
                
                if ($company == '') $state="INPUT";
                else {
                    $count=V_DB::count('v_work_list','client_company_name='.$company);
                    if ($count>0) $state="EXISTCOMPANY";
                }
                
                if ($phone == '')$state="INPUT";
                else {
                    $count=V_DB::count('v_work_list_phones','phone='.$phone);
                    if ($count>0) $state="EXISTPHONE";
                    else if (!V_Check::phone($_POST['cphone'])) $state="PHONEERROR";
                }
                
            	if ( $date == '') $state="INPUT";
                else if (!V_Check::date($_POST['cdate'])) $state="DATEERROR";
                if ($state=="OK") {
                	if (V_DB::insert('v_work_list',Array(
                		Array ('name' => 'user_add_id','value' => '"'.V_User::getId().'"'),
                		Array ('name' => 'user_add_issend','value' => 0),
            			Array ('name' => 'user_work_id','value' => 0),
            			Array ('name' => 'user_work_isget','value' => 0),
                		Array ('name' => 'client_company_name','value' => '"'.$company.'"'),
                		Array ('name' => 'client_city_id','value' => V_User::getCity()),
                		Array ('name' => 'client_site','value' => '""'),
            			Array ('name' => 'list_add_date','value' => 'NOW()'),
            			Array ('name' => 'list_is_sign','value' => 0)
                	))){ 
                		$insert_id=mysql_insert_id();
                		echo $insert_id;
                		V_DB::insert('v_work_list_phones',Array(
                			Array ('name' => 'list_id','value' => $insert_id),
                			Array ('name' => 'phone','value' => '"'.$phone.'"')
                		));
                		V_DB::insert('v_work_list_states',Array(
                			Array ('name' => 'list_id','value' => $insert_id),
                			Array ('name' => 'state_date','value' => '"'.$date.'"')
                		));
                		V_DB::insert('v_work_list_services',Array(
                			Array ('name' => 'list_id','value' => $insert_id)
                		));
                	}
                	else echo "ERROR";
                } else echo $state;
            }
        }
        // ------------------------------------------------------------------------------------------
    	// ----------Добавление и получение дополнительных полей рабочего листа----------------------
    	// ------------------------------------------------------------------------------------------
		function comment_add () {
            // Если форма отправлена - проверка данных
            if (isset ($_POST['action']) and $_POST['action']=='add') {
            	$state="OK";
            	if (trim($_POST['comment']) == '')
                    $state="INPUT";
                if ($state=="OK") {
                	if (V_DB::insert('v_work_list_comments',Array(
                		Array ('name' => 'list_id','value' => '"'.$_POST['id'].'"'),
                		Array ('name' => 'user_id','value' => '"'.V_User::getId().'"'),
                		Array ('name' => 'comment','value' => '"'.$_POST['comment'].'"'),
                		Array ('name' => 'date','value' => 'NOW()')
                	))
                	and V_DB::insert('v_work_list_dates',Array(
                		Array ('name' => 'list_id','value' => '"'.V_DB::escape($_POST['id']).'"'),
            			Array ('name' => 'user_id','value' => '"'.V_User::getId().'"'),
            			Array ('name' => 'date','value' => 'NOW()'),
            			Array ('name' => 'action','value' => '"append"')
                	))
                	) echo "OK";
                	else echo "ERROR";
                } else echo $state;
            }
        }
		function phone_add () {
            // Если форма отправлена - проверка данных
            if (isset ($_POST['action']) and $_POST['action']=='add') {
            	$state="OK";
            	if (trim($_POST['phone']) == '')
                    $state="INPUT";
                if (!V_Check::phone($_POST['phone']))
                    $state="PHONEERROR";
                else { 
                	$count=V_DB::count('v_work_list_phones','phone='.$phone);
                    if ($count>0) $state="EXISTPHONE";
                }
                if ($state=="OK") {
                	if (V_DB::insert('v_work_list_phones',Array(
                		Array ('name' => 'list_id','value' => '"'.V_DB::escape($_POST['id']).'"'),
                		Array ('name' => 'phone','value' => '"'.V_DB::escape($_POST['phone']).'"')
                	))
                	and V_DB::insert('v_work_list_dates',Array(
                		Array ('name' => 'list_id','value' => '"'.V_DB::escape($_POST['id']).'"'),
            			Array ('name' => 'user_id','value' => '"'.V_User::getId().'"'),
            			Array ('name' => 'date','value' => 'NOW()'),
            			Array ('name' => 'action','value' => '"append"')
                	))
                	) echo "OK";
                	else echo "ERROR";
                } else echo $state;
            }
        }
        function phone_edit () {
            // Если форма отправлена - проверка данных
            if (isset ($_POST['action']) and $_POST['action']=='edit') {
            	$state="OK";
                if (!V_Check::phone($_POST['phone']) and trim($_POST['phone'])!='')
                    $state="PHONEERROR";
                if ($state=="OK") {
                	if (V_DB::update('v_work_list_phones',V_DB::escape($_POST['id']),Array(
                		Array ('name' => 'phone','value' => '"'.V_DB::escape($_POST['phone']).'"'),
                	))
                	and V_DB::insert('v_work_list_dates',Array(
                		Array ('name' => 'list_id','value' => '"'.V_DB::escape($_POST['id']).'"'),
            			Array ('name' => 'user_id','value' => '"'.V_User::getId().'"'),
            			Array ('name' => 'date','value' => 'NOW()'),
            			Array ('name' => 'action','value' => '"edit"')
                	))
                	) echo "OK";
                	else echo "ERROR";
                } else echo $state;
            }
        }
		function phone_delete () {
        	$phoneid=$_POST['phoneid'];
            if (V_DB::query('DELETE FROM v_work_list_phones WHERE id='.$phoneid)) echo "OK";
        }
        function phone_get () {
        	// Получение номеров телефона листа
            $phone_res=V_DB::query(
            	'SELECT phone, id FROM v_work_list_phones '.
            	'WHERE list_id='.V_DB::escape($_POST['id']));
            if (!empty($phone_res)) {
            	foreach ($phone_res as $phone) {
                    $phones[]=
                    	'<span id="phone_el'.$phone['id'].'" class="button" style="line-height:26px;"'.
                    		'onclick="phone.edit_show('.$phone['id'].')">'.$phone['phone'].'</span>'.
                    	'<input type="text" id="phone_edit_el'.$phone['id'].'" style="display:none" '.
                    		'onblur="phone.edit_hide('.$phone['id'].')">';
            	}
                echo implode(' ',$phones);
            }
        }
		function sms_get () {
        	// Получение номеров телефона листа
            $sms_res=V_DB::fetch('SELECT sms_all, sms_left, sms_nopaid, sms_present, sms_login, sms_pass '.
            					'FROM v_work_list_sms '.
            					'WHERE list_id='.V_DB::escape($_POST['id']));
            if (!empty($sms_res)) {
                $sms_list=
                    '<span>Зачислено : '.$sms['sms_all'].'</span> '.
                    	'<span class="button" onclick="sms.edit_show(\'all\')">зачислить</span><br />'.
                	'<span> Осталось :  '.$sms['sms_left'].'</span> '.
                		'<span class="button" onclick="sms.edit_show(\'left\')">изменить</span><br />'.
                	'<span>Не оплачено :'.$sms['sms_nopaid'].'</span> '.
                		'<span class="button" onclick="sms.edit_show(\'nopaid\')">изменить</span><br />'.
                	'<span>В подарок :'.$sms['sms_present'].'</span> '.
                		'<span class="button" onclick="sms.edit_show(\'present\')">изменить</span><br />'.
                	'<span>Логин :'.$sms['sms_login'].'</span> '.
                		'<span class="button" onclick="sms.edit_show(\'login\')">изменить</span><br />'.
                	'<span>Пароль :'.$sms['sms_pass'].'</span> '.
                		'<span class="button" onclick="sms.edit_show(\'pass\')">изменить</span><br />';
                echo $sms_list;
            };
        }
		function sms_edit () {
            // Если форма отправлена - проверка данных
            if (isset ($_POST['action']) and $_POST['action']=='edit') {
            	$state="OK";
            	switch ($_POST['edit_type']){
                	case 'all':$tp='all'; break;
                	case 'all':$tp='all'; break;
                	case 'left':$tp='left'; break;
                	case 'nopaid':$tp='nopaid'; break;
                	case 'present':$tp='present'; break;
                	case 'city':$tp='city'; break;
                	case 'login':$tp='login'; break;
                	case 'pass':$tp='pass'; break;
                }
                if (!V_Check::number($_POST['sms'] or $tp=='pass' or $tp=='login') and trim($_POST['sms'])!='')
                    $state="SMSERROR";
                if (!V_Check::number($_POST['money']) and ($tp=='all' or $tp=='city')) 
                	$state="SMSMONEYERROR";
                if ($state=="OK") {
                	if ($tp=='all') {
                		$sms=V_DB::fetch('SELECT sms_count FROM v_work_list_city WHERE id='.V_User::getCity());
                		$sms_res=-1;
                		if (!empty($sms)) $sms_res=$sms['sms_count']-$_POST['sms'];	
                		if ($sms_res>0) {
                			V_DB::update('v_work_list_city',V_User::getCity(),Array(
                					Array ('name' => 'sms_count','value' => $sms_res)
                				));
                				V_DB::insert('v_sms_list_client',Array(
                					Array ('name' => 'send_city_id','value' => V_User::getCity()),
                					Array ('name' => 'target_list_id','value' => V_DB::escape($_POST['id'])),
                					Array ('name' => 'sms_count','value' => V_DB::escape($_POST['sms'])),
                					Array ('name' => 'sms_money','value' => V_DB::escape($_POST['money'])),
                					Array ('name' => 'send_date','value' => 'NOW()')
                				));
                			$list=V_DB::fetch('SELECT id, sms_all FROM v_work_list_sms WHERE list_id='.
                					V_DB::escape($_POST['id']));
                			if (!empty($list)) { 
                				if (V_DB::update('v_work_list_sms',$list['id'],Array(
                					Array ('name' => 'sms_all',
                							'value' => $list['sms_all']+V_DB::escape($_POST['sms']))
                				))) echo "OK";
                			} else {
                				if (V_DB::insert('v_work_list_sms',Array(
                					Array ('name' => 'sms_all','value' => V_DB::escape($_POST['sms'])),
                					Array ('name' => 'list_id','value' => V_DB::escape($_POST['id']))
                				))) echo "OK";
                			}
                		} else echo "SMSCOUNTERROR";
                	}
                	elseif ($tp=='city') {
                		$sms=V_DB::fetch('SELECT sms_count FROM v_work_list_city WHERE id='.V_User::getCity());
                		$sms_res=-1;
                		if (!empty($sms)) $sms_res=$sms['sms_count']-$_POST['sms'];	
                		if ($sms_res>0) {
                			$sms=V_DB::fetch('SELECT sms_count FROM v_work_list_city WHERE id='.
                					V_DB::escape($_POST['id']));
                			if (!empty($sms)) {
                				V_DB::update('v_work_list_city',V_User::getCity(),Array(
                					Array ('name' => 'sms_count','value' => $sms_res)
                				));
                				V_DB::update('v_work_list_city',V_DB::escape($_POST['id']),Array(
                					Array ('name' => 'sms_count',
                							'value' => $sms['sms_count']+V_DB::escape($_POST['sms']))
                				));
                				if (V_DB::insert('v_sms_list_city',Array(
                					Array ('name' => 'send_city_id','value' => V_User::getCity()),
                					Array ('name' => 'target_city_id','value' => V_DB::escape($_POST['id'])),
                					Array ('name' => 'sms_count','value' => V_DB::escape($_POST['sms'])),
                					Array ('name' => 'sms_money','value' => V_DB::escape($_POST['money'])),
                					Array ('name' => 'send_date','value' => 'NOW()')
                				))) echo 'OK';
                			}
                		} else echo "SMSCOUNTERROR";
                	} else {
                		$list=V_DB::query('SELECT id FROM v_work_list_sms WHERE list_id='.
                				V_DB::escape($_POST['id']));
                		if (!empty($list)) { 
                			if (V_DB::update('v_work_list_sms',$list['id'],Array(
                				Array ('name' => 'sms_'.$tp,'value' => '"'.V_DB::escape($_POST['sms']).'"')
                			))) echo "OK";
                		} else {
                			if (V_DB::insert('v_work_list_sms',Array(
                				Array ('name' => 'sms_'.$tp,'value' => V_DB::escape($_POST['sms'])),
                				Array ('name' => 'list_id','value' => V_DB::escape($_POST['id']))
                			))) echo "OK";
                		}
                	}
                } else echo $state;
            }
        }
		function email_add () {
            // Если форма отправлена - проверка данных
            if (isset ($_POST['action']) and $_POST['action']=='add') {
            	$state="OK";
            	if (trim($_POST['email']) == '')
                    $state="INPUT";
                if (!V_Check::email($_POST['email']))
                    $state="EMAILERROR";
                if ($state=="OK") {
                	if (V_DB::insert('v_work_list_emails',Array(
                		Array ('name' => 'list_id','value' => '"'.V_DB::escape($_POST['id']).'"'),
                		Array ('name' => 'email','value' => '"'.V_DB::escape($_POST['email']).'"')
                	))
                	and V_DB::insert('v_work_list_dates',Array(
                		Array ('name' => 'list_id','value' => '"'.V_DB::escape($_POST['id']).'"'),
            			Array ('name' => 'user_id','value' => '"'.V_User::getId().'"'),
            			Array ('name' => 'date','value' => 'NOW()'),
            			Array ('name' => 'action','value' => '"append"')
                	))
                	) echo "OK";
                	else echo "ERROR";
                } else echo $state;
            }
        }
		function contact_add () {
            // Если форма отправлена - проверка данных
            if (isset ($_POST['action']) and $_POST['action']=='add') {
            	$state="OK";
            	if (trim($_POST['name']) == '')
                    $state="INPUT";
                $contact_phone = V_DB::escape($_POST['phone']);
                if (!V_Check::phone($contact_phone) and trim($contact_phone!=''))
                    $state="PHONEERROR";
            	else {
                	$count=V_DB::count('v_work_list_phones','contact_phone='.$contact_phone);
                    if ($count>0) $state="EXISTPHONE";
                }
                if ($state=="OK") {
                	if (V_DB::insert('v_work_list_contacts',Array(
                		Array ('name' => 'list_id','value' => '"'.V_DB::escape($_POST['id']).'"'),
                		Array ('name' => 'contact_name','value' => '"'.V_DB::escape($_POST['name']).'"'),
                		Array ('name' => 'contact_visible','value' => '"'.V_DB::escape($_POST['visible']).'"'),
						Array ('name' => 'contact_phone','value' => '"'.V_DB::escape($_POST['phone']).'"'),
						Array ('name' => 'contact_post','value' => '"'.V_DB::escape($_POST['post']).'"'),
						Array ('name' => 'contact_comment','value' => '"'.V_DB::escape($_POST['comment']).'"')
                	))
                	and V_DB::insert('v_work_list_dates',Array(
                		Array ('name' => 'list_id','value' => '"'.V_DB::escape($_POST['id']).'"'),
            			Array ('name' => 'user_id','value' => '"'.V_User::getId().'"'),
            			Array ('name' => 'date','value' => 'NOW()'),
            			Array ('name' => 'action','value' => '"append"')
                	))
                	) echo "OK";
                	else echo "ERROR";
                } else echo $state;
            }
        }
		function contact_get () {
			// Получение контактов листа
            $contact_res=V_DB::fetchAll(
            	'SELECT id, contact_name, contact_phone, contact_post, contact_comment, contact_visible '.
            	'FROM v_work_list_contacts '.
            	'WHERE list_id='.V_DB::escape($_POST['id'])
            );
            $list=V_DB::fetch(
            	'SELECT id, user_add_id, user_work_id, client_city_id, list_is_sign '.
            	'FROM v_work_list '.
            	'WHERE id='.V_DB::escape($_POST['id']).' LIMIT 0,1'
            );
            if (!empty($contact) and !empty($list)) {
            	foreach ($contact_res as $contact) {
                    if ($contact['contact_visible']!=0 or 
                    	(V_User::getGroup()==0 and 
                    		($list['client_city_id']==V_User::getCity() or V_User::getCity()==0)) or
                    	(V_User::getId()==$list['user_add_id'] and $list['list_is_sign']==0) or
                    	(V_User::getId()==$list['user_work_id'] and $list['list_is_sign']==0)
                    )
                    $contacts[]=
                    	'<h6 id="contact_el'.$contact['id'].'">'.
                    		'<a href="#" class="contact_name">'.$contact['contact_name'].'</a>'.
                    	'</h6>'.
                    	'<div id="contact_el_data'.$contact['id'].'">'.
                    		'<span class="contact_phone">'.$contact['contact_phone'].'</span<br />'.
                    		'<span class="contact_post">'.$contact['contact_post'].'</span><br />'.
                    		'<div class="contact_comment">'.$contact['contact_comment'].'</div>'.
                    		'<span style="display:none" class="contact_visible">'.$contact['contact_visible'].'</span> '.
                    		'<span class="button" onclick="contact.del('.$contact['id'].')">удалить</span> '.
                    		'<span class="button" onclick="contact.edit_show('.$contact['id'].')">изменить</span>'.
                    	'</div>';
            	}
                if (sizeof($contacts)>0) echo '<div id="contact_list_el">'.implode($contacts).'</div>';
            }
        }
		function contact_delete () {
        	$contactid=$_POST['contactid'];
            if (V_DB::exec('DELETE FROM v_work_list_contacts WHERE id='.$contactid)) echo "OK";
        }
		function contact_edit () {
            // Если форма отправлена - проверка данных
            if (isset ($_POST['action']) and $_POST['action']=='edit') {
            	$state="OK";
            	if (trim($_POST['name']) == '')
                    $state="INPUT";
                if (!V_Check::phone($_POST['phone']) and trim($_POST['phone'])!='')
                    $state="PHONEERROR";
                if ($state=="OK") {
                	if (V_DB::update('v_work_list_contacts',V_DB::escape($_POST['id']),Array(
                		Array ('name' => 'contact_name','value' => '"'.V_DB::escape($_POST['name']).'"'),
                		Array ('name' => 'contact_visible','value' => '"'.V_DB::escape($_POST['visible']).'"'),
						Array ('name' => 'contact_phone','value' => '"'.V_DB::escape($_POST['phone']).'"'),
						Array ('name' => 'contact_post','value' => '"'.V_DB::escape($_POST['post']).'"'),
						Array ('name' => 'contact_comment','value' => '"'.V_DB::escape($_POST['comment']).'"')
                	))
                	and V_DB::insert('v_work_list_dates',Array(
                		Array ('name' => 'list_id','value' => '"'.V_DB::escape($_POST['id']).'"'),
            			Array ('name' => 'user_id','value' => '"'.V_User::getId().'"'),
            			Array ('name' => 'date','value' => 'NOW()'),
            			Array ('name' => 'action','value' => '"edit"')
                	))
                	) echo "OK";
                	else echo "ERROR";
                } else echo $state;
            }
        }
		function service_get () {
			// Получение контактов листа
            $service_res=V_DB::query(
            	'SELECT ls.id, ls.service_comment, sv.service_name, cm.service_company, st.service_state '.
            	'FROM v_work_list_services AS ls '.
            	'LEFT JOIN v_service_list AS sv ON sv.id=ls.service_id '.
            	'LEFT JOIN v_service_list_states AS st ON st.id=ls.service_state_id '.
            	'LEFT JOIN v_service_list_company AS cm ON cm.id=ls.service_company_id '.
            	'WHERE ls.list_id='.$_POST['id']
            );
            if (!empty($service_res)) {
            	foreach ($service_res as $service) {
                    $services[]=
                    	'<h6 id="service_el'.$service['id'].'">'.
                    		'<a href="#" class="service_name">'.$service['service_name'].'</a>'.
                    	'</h6>'.
                    	'<div id="service_el_data'.$service['id'].'">'.
                    		'Компания: <span class="service_company">'.$service['service_company'].'</span<br />'.
                    		'Статус: <span class="service_state">'.$service['service_state'].'</span><br />'.
                    		'<div class="service_comment">'.$service['service_comment'].'</div>'.
                    		'<span class="button" onclick="service.del('.$service['id'].')">удалить</span> '.
                    	'</div>';
            	}
                if (sizeof($services)>0) echo '<div id="service_list_el">'.implode($services).'</div>';
            }
        }
		function service_add () {
            // Если форма отправлена - проверка данных
            if (isset ($_POST['action']) and $_POST['action']=='add') {
            	$state="OK";
            	$count=V_DB::count(
            		'v_work_list_services ',
            		'list_id='.$_POST['id'].' AND service_id='.$_POST['name']);
            	if ($count>0) $state="SERVICEEXIST";        
                if ($state=="OK") {
                	if (V_DB::insert('v_work_list_services',Array(
                		Array ('name' => 'list_id','value' => '"'.V_DB::escape($_POST['id']).'"'),
                		Array ('name' => 'service_id','value' => '"'.V_DB::escape($_POST['name']).'"'),
						Array ('name' => 'service_company_id','value' => '"'.V_DB::escape($_POST['company']).'"'),
						Array ('name' => 'service_state_id','value' => '"'.V_DB::escape($_POST['state']).'"'),
						Array ('name' => 'service_comment','value' => '"'.V_DB::escape($_POST['comment']).'"')
                	))
                	and V_DB::insert('v_work_list_dates',Array(
                		Array ('name' => 'list_id','value' => '"'.V_DB::escape($_POST['id']).'"'),
            			Array ('name' => 'user_id','value' => '"'.V_User::getId().'"'),
            			Array ('name' => 'date','value' => 'NOW()'),
            			Array ('name' => 'action','value' => '"append"')
                	))) echo "OK";
                	else echo "ERROR";
                } else echo $state;
            }
        }
		function service_delete () {
        	$serviceid=$_POST['serviceid'];
            if (V_DB::exec('DELETE FROM v_work_list_services WHERE id='.$serviceid))	{
            	echo "OK";
            }
        }
		function jobs_add () {
            // Если форма отправлена - проверка данных
            if (isset ($_POST['action']) and $_POST['action']=='add') {
            	$state="OK";
            	$list=explode(',',V_DB::escape($_POST['list_id']));
            	// Получение Id пользователя
            	if ($_POST['target_user_id']==-1) {
            		$t_user_id=-1;
            		$t_isget = 0;
            	}
            	else {
            		$t_user=V_DB::fetch(
            			'SELECT id FROM v_user_list WHERE login="'.V_DB::escape($_POST['target_user_id']).'"'
            		);
                	if (!empty($t_user)) {
                		$t_user_id=$t_user['id'];
                		$t_isget = 1;
                	} else $state="TARGETERROR";
            	}
                if ($state=="OK") {
                	if (V_DB::insert('v_job_list',Array(
                		Array ('name' => 'work_user_id','value' => '"'.$t_user_id.'"'),
                		//group_id на 1 больше, если 0 - всем пользователям
                		Array ('name' => 'target_group_id','value' => '"'.V_DB::escape($_POST['target_group_id']).'"'),
                		Array ('name' => 'send_user_id','value' => '"'.V_User::getId().'"'),
                		Array ('name' => 'message','value' => '"'.V_DB::escape($_POST['message']).'"'),
                		Array ('name' => 'target_isget','value' => '"'.$t_isget.'"')
                	))) echo "OK";
                	else echo "ERROR";
                	$job_id=mysql_insert_id();
                	for ($i=0;$i<sizeof($list);$i++)
                	V_DB::insert('v_job_list_items',Array(
                		Array ('name' => 'job_id','value' => '"'.$job_id.'"'),
                		Array ('name' => 'list_id','value' => '"'.$list[$i].'"')
                	));
                } else echo $state;
            }
        }
        function jobs_getwork () {
        	if (isset ($_POST['id']) and $_POST['id']!='') {
                if (V_DB::exec(
                	'UPDATE v_job_list SET work_user_id='.V_User::getId().', target_isget=1'.
                    ' WHERE id='.V_DB::escape($_POST['id']))
                ) echo "OK";
        	}
        }
		function jobs_appwork () {
        	if (isset ($_POST['id']) and $_POST['id']!='') {
                if (V_DB::exec('UPDATE v_job_list SET work_isapp=1 WHERE id='.V_DB::escape($_POST['id'])))
                	echo "OK";
        	}
        }
		function jobs_delwork () {
        	if (isset ($_POST['id']) and $_POST['id']!='') {
        		$row = V_DB::fetch ('SELECT id, work_user_id, send_user_id, message '.
            						'FROM v_job_list '.'WHERE id='.V_DB::escape($_POST['id']));
        		if (!empty($row)){	
    				//Получение рабочих листов, связанных с заданием
    				$res=V_DB::fetchAll('SELECT list_id FROM v_job_list_items WHERE job_id='.$row['id']);
    				if (!empty($res)) {
    					foreach ($res as $item) $t_list[]=$item['list_id'];
    				}
    				!empty($t_list) ? $list=implode(', ',$t_list) :  $list='';
        			//Добавление в архив
					V_DB::insert('v_job_list_archive',Array(
                		Array ('name' => 'work_user_id','value' => '"'.$row['work_user_id'].'"'),
                		Array ('name' => 'send_user_id','value' => '"'.$row['send_user_id'].'"'),
                		Array ('name' => 'message','value' => '"'.$row['message'].'"'),
                		Array ('name' => 'list','value' => '"'.$list.'"'),
                	));
				
                	if (V_DB::exec('DELETE FROM v_job_list WHERE id='.V_DB::escape($_POST['id']))
                	and (V_DB::exec('DELETE FROM v_job_list_items WHERE job_id='.V_DB::escape($_POST['id'])))
                	) echo "OK";
        		}
        	}
        }
        // ------------------------------------------------------------------------------------------
    	// ----------Страница редактирования рабочего листа------------------------------------------
    	// ------------------------------------------------------------------------------------------
		function edit () {
            // Получение рабочего листа
            $wl=V_DB::fetch(
            	'SELECT id, client_company_name, client_category_id, list_add_date, '.
            	'client_site, client_city_id, list_is_sign, user_add_issend, user_work_isget, '.
            	'user_add_id, user_work_id '.
            	'FROM v_work_list '.
            	'WHERE id='.V_DB::escape($router->getId()).' LIMIT 0,1');
			// Создание массива с состояниями рабочего листа
            $state=V_DB::query('SELECT list_id, state_id, state_comment, '.
            					"DATE_FORMAT(state_date,'%Y-%m-%d') AS state_date ".
            					'FROM v_work_list_states '.
            					'WHERE list_id='.V_DB::escape($router->getId()).' LIMIT 0,1');
            if (!empty($state)) {
            	$wl['list_state_id']=$state['state_id'];
            	$wl['list_state_date']=$state['state_date'];
            	$wl['list_state_comment']=$state['state_comment'];
            }
            // Получение информации об изменениях, если запрашивает админ
            if (V_User::getId()==0) {
                $dtl=V_DB::fetch('SELECT dt.action, dt.date, us.name  '.
            					'FROM v_work_list_dates AS dt LEFT JOIN v_user_list AS us ON dt.user_id=us.id '.
            					'WHERE list_id='.V_DB::escape($router->getId()));
            }
            // Получение информации о компании
            $cl=V_DB::fetch('SELECT id, list_id, legal_name, notlegal_name, sign_user_name, sign_user_post, sign_basement, '.
            					'contract_num, legal_address, notlegal_address, mail_address, '.
            					"first_purchase, phone ".
            					'FROM v_company_list '.
            					'WHERE list_id='.V_DB::escape($router->getId()).' LIMIT 0,1');
            // Получение пользователя добавившего рабочий лист
            $addus=V_DB::fetch('SELECT us.name '.
            					'FROM v_work_list AS ls LEFT JOIN v_user_list AS us ON ls.user_add_id=us.id '.
            					'WHERE ls.id='.V_DB::escape($router->getId()).' LIMIT 0,1');
            if (!empty($addus)) $wl['user_add']=$addus['name'];
            // Получение пользователя работающего с рабочим листом
            $workus=V_DB::fetch('SELECT us.name '.
            					'FROM v_work_list AS ls LEFT JOIN v_user_list AS us ON ls.user_work_id=us.id '.
            					'WHERE ls.id='.V_DB::escape($router->getId()).' LIMIT 0,1');
            if (!empty($workus)) $wl['user_work']=$workus['name'];
			// Получение e-mail листа
            $email_res=V_DB::fetchAll(
            	'SELECT email FROM v_work_list_emails '.
            	'WHERE list_id='.V_DB::escape($router->getId())
            );
            if (!empty($email_res)) {
            	foreach ($email_res as $email) 
                    $emails[]=$email['email'];
                $wl['client_company_emails']=implode(', ',$emails);
            }
			// Получение состояний листа
            $state_res=V_DB::fetchAll('SELECT id, state FROM v_state_list');
            if (!empty($state_res)) {
            	foreach ($state_res as $state)
                    $wl['list_states'][]=$state['state'];
            }
			// Получение списка должностей контакта
            $post_res=V_DB::fetchAll('SELECT post_name FROM v_contact_list_post');
            if (!empty($post_res)) {
            	foreach ($post_res as $post)
                    $wl['contact_post_list'][]=$post['post_name'];
            }
			// Получение списка категорий компании
            $cat_res=V_DB::fetchAll('SELECT id, category_name FROM v_category_list ORDER BY category_name');
            if (!empty($cat_res)) {
            	foreach ($cat_res as $category) {
                    $category_list['id']=$category['id'];
                    $category_list['name']=$category['category_name'];
                    $wl['client_category_list'][]=$category_list;
            	}
            }
			// Получение списка названий услуг
            $service_res=V_DB::fetchAll("SELECT id, service_name ".
            					'FROM v_service_list');
            if ($result) {
            	for ($i=0;$i<V_DB::num_rows($result);$i++) {
                    $service=V_DB::fetch_array($result);
                    $service_array['name']=$service['service_name'];
                    $service_array['id']=$service['id'];
                    $wl['service_name_list'][]=$service_array;
            	}
            }
			// Получение списка компаний, предоставляющих услуги
            $result=V_DB::query("SELECT service_company ".
            					'FROM v_service_list_company');
            if ($result) {
            	for ($i=0;$i<V_DB::num_rows($result);$i++) {
                    $service_company=V_DB::fetch_array($result);
                    $wl['service_company_list'][]=$service_company['service_company'];
            	}
            }
			// Получение списка статусов работы с клиентом
            $result=V_DB::query("SELECT service_state ".
            					'FROM v_service_list_states');
            if ($result) {
            	for ($i=0;$i<V_DB::num_rows($result);$i++) {
                    $service_state=V_DB::fetch_array($result);
                    $wl['service_state_list'][]=$service_state['service_state'];
            	}
            }
			// Получение комментариев листа
            $result=V_DB::query("SELECT DATE_FORMAT(comm.date,'%Y-%m-%d') AS date, comment, name ".
            			'FROM v_work_list_comments AS comm LEFT JOIN v_user_list AS user '.
            			'ON comm.user_id=user.id '.
            			'WHERE comm.list_id='.V_DB::escape($router->getId()));
            $comments = Array();
            if ($result) {
            	for ($i=0;$i<V_DB::num_rows($result);$i++) {
                    $comment=V_DB::fetch_array($result);
                    $comments[]='<span style="color:#733">'.$comment['date'].': добавил '.$comment['name'].
                    			'</span><br />'.$comment['comment'];
            	}
                $wl['list_comments']=implode('<br /> ',$comments);
            }
            // Получение информации о городах
            $result=V_DB::query('SELECT id,city FROM v_work_list_city');
            if ($result) {
            	for ($i=0;$i<V_DB::num_rows($result);$i++) {
                	$city=V_DB::fetch_array($result);
                	$city_array['id']=$city['id'];
                	$city_array['name']=$city['city'];
                	$wl['city_list'][]=$city_array;
            	}
            }
            // Изменение рабочего листа
            if (isset($_POST['action']) and $_POST['action']=="edit") {
            	// Проверка рабочего листа
            	$wl['client_company_name']=V_DB::escape($_POST['client_company_name']);
            	$wl['client_category_id']=V_DB::escape($_POST['client_category_id']);
            	$wl['client_site']=V_DB::escape($_POST['client_site']);
            	$wl['client_city']=V_DB::escape($_POST['client_city']);
            	// Применение параметров, если нет ошибок
            	if (true) {
            		// Обновление статистики
            		V_DB::insert('v_work_list_dates',Array(
                			Array ('name' => 'list_id','value' => '"'.$router->getId().'"'),
            				Array ('name' => 'user_id','value' => '"'.V_User::getId().'"'),
            				Array ('name' => 'date','value' => 'NOW()'),
            				Array ('name' => 'action','value' => '"edit"'),
                		));
            		V_DB::update ('v_work_list',$router->getId(),Array(
            			Array ('name' => 'client_company_name', 'value' => '"'.$wl['client_company_name'].'"'),
            			Array ('name' => 'client_category_id', 'value' => '"'.$wl['client_category_id'].'"'),
            			Array ('name' => 'client_site', 'value' => '"'.$wl['client_site'].'"'),
            			Array ('name' => 'client_city_id', 'value' => $wl['client_city']),
            			Array ('name' => 'list_edit_date', 'value' => 'NOW()')
            		));
            		$router->setPage('worklist','edit',$router->getId());
            	}
            }
            $this->assign('wl',$wl);
            $this->assign('cl',$cl);
            $this->assign('dtl',$cl);
            $this->assign('page_title','Редактирование рабочего листа');
            $this->display('header.tpl');
            $this->display('pages/worklist/edit.tpl');
            $this->display('footer.tpl');
        }
        // ------------------------------------------------------------------------------------------
    	// ----------Подписать рабочий лист----------------------------------------------------------
    	// ------------------------------------------------------------------------------------------
        function signlist () {
        	$router=V_Engine::create('Router');
        	$result=V_DB::select('v_company_list','list_id='.V_DB::escape($router->getId()));
            if ($result and V_DB::num_rows($result)>0) {
            	V_DB::update ('v_work_list',$router->getId(),Array (
            		Array ('name' => 'list_is_sign','value' => 1)
            	));
            	$router->setPage('worklist','edit',$router->getId());
            } else {
            	$router->setPage('worklist','edit',$router->getId());
            }
        }
        // ------------------------------------------------------------------------------------------
    	// ----------Добавление информации о компании------------------------------------------------
    	// ------------------------------------------------------------------------------------------
		function company_edit () {
			V_Engine::load('DB');
			V_Engine::load('Check');
            $router=V_Engine::create('Router');
            $user=V_Engine::create('User');
            // Получение информации о компании
            $result=V_DB::query('SELECT id FROM v_company_list '.
            					'WHERE list_id='.V_DB::escape($router->getId()).' LIMIT 0,1');
            if ($result)
                $cl=V_DB::fetch_array($result);
            // Проверка информации
            $cl['legal_name']=V_DB::escape($_POST['legal_name']);
            $cl['notlegal_name']=V_DB::escape($_POST['notlegal_name']);
            $cl['sign_user_name']=V_DB::escape($_POST['sign_user_name']);
            $cl['sign_user_post']=V_DB::escape($_POST['sign_user_post']);
            $cl['sign_basement']=V_DB::escape($_POST['sign_basement']);
            $cl['contract_num']=V_DB::escape($_POST['contract_num']);
            $cl['legal_address']=V_DB::escape($_POST['legal_address']);
            $cl['notlegal_address']=V_DB::escape($_POST['notlegal_address']);
            $cl['mail_address']=V_DB::escape($_POST['mail_address']);
            $cl['first_purchase']=V_DB::escape($_POST['first_purchase']);
            $cl['phone']=V_DB::escape($_POST['phone']);
            
            if (isset($_POST['action']) and $_POST['action']=="edit") {
            	// Применение параметров, если нет ошибок
            	if ((V_Check::phone($cl['phone'])||$cl['phone']=='') && trim($cl['contract_num'])!='') {
            		// Обновление статистики
            		V_DB::insert('v_work_list_dates',Array(
                			Array ('name' => 'list_id','value' => '"'.$router->getId().'"'),
            				Array ('name' => 'user_id','value' => '"'.V_User::getId().'"'),
            				Array ('name' => 'date','value' => 'NOW()'),
            				Array ('name' => 'action','value' => '"edit"'),
                		));
                	// Обновление информации
            		V_DB::update ('v_company_list',$cl['id'],Array(
            			Array ('name' => 'legal_name', 'value' => '"'.$cl['legal_name'].'"'),
            			Array ('name' => 'notlegal_name', 'value' => '"'.$cl['notlegal_name'].'"'),
            			Array ('name' => 'sign_user_name', 'value' => '"'.$cl['sign_user_name'].'"'),
            			Array ('name' => 'sign_user_post', 'value' => '"'.$cl['sign_user_post'].'"'),
            			Array ('name' => 'sign_basement', 'value' => '"'.$cl['sign_basement'].'"'),
            			Array ('name' => 'contract_num', 'value' => '"'.$cl['contract_num'].'"'),
            			Array ('name' => 'legal_address', 'value' => '"'.$cl['legal_address'].'"'),
            			Array ('name' => 'notlegal_address', 'value' => '"'.$cl['notlegal_address'].'"'),
            			Array ('name' => 'mail_address', 'value' => '"'.$cl['mail_address'].'"'),
            			Array ('name' => 'first_purchase', 'value' => '"'.$cl['first_purchase'].'"'),
            			Array ('name' => 'phone', 'value' => '"'.$cl['phone'].'"'),
            			Array ('name' => 'list_id', 'value' => '"'.V_DB::escape($router->getId()).'"')
            		));
            	} $router->setPage('worklist','edit',$router->getId());
            } elseif (isset($_POST['action']) and $_POST['action']=="add") {
            	// Применение параметров, если нет ошибок
            	if ((V_Check::phone($cl['phone'])||$cl['phone']=='') && trim($cl['contract_num'])!='') {
            		// Обновление статистики
            		V_DB::insert('v_work_list_dates',Array(
                		Array ('name' => 'list_id','value' => '"'.$router->getId().'"'),
            			Array ('name' => 'user_id','value' => '"'.V_User::getId().'"'),
            			Array ('name' => 'date','value' => 'NOW()'),
            			Array ('name' => 'action','value' => '"edit"'),
                	));
                	// Добавление информации
            		V_DB::insert ('v_company_list',Array(
            			Array ('name' => 'legal_name', 'value' => '"'.$cl['legal_name'].'"'),
            			Array ('name' => 'notlegal_name', 'value' => '"'.$cl['notlegal_name'].'"'),
            			Array ('name' => 'sign_user_name', 'value' => '"'.$cl['sign_user_name'].'"'),
            			Array ('name' => 'sign_user_post', 'value' => '"'.$cl['sign_user_post'].'"'),
            			Array ('name' => 'sign_basement', 'value' => '"'.$cl['sign_basement'].'"'),
            			Array ('name' => 'contract_num', 'value' => '"'.$cl['contract_num'].'"'),
            			Array ('name' => 'legal_address', 'value' => '"'.$cl['legal_address'].'"'),
            			Array ('name' => 'notlegal_address', 'value' => '"'.$cl['notlegal_address'].'"'),
            			Array ('name' => 'mail_address', 'value' => '"'.$cl['mail_address'].'"'),
            			Array ('name' => 'first_purchase', 'value' => '"'.$cl['first_purchase'].'"'),
            			Array ('name' => 'phone', 'value' => '"'.$cl['phone'].'"'),
            			Array ('name' => 'list_id', 'value' => '"'.V_DB::escape($router->getId()).'"')
            		));
            	} $router->setPage('worklist','edit',$router->getId());
            }
        }
        // ------------------------------------------------------------------------------------------
    	// ----------Удаление рабочего листа---------------------------------------------------------
    	// ------------------------------------------------------------------------------------------
        function delete () {
            $router=V_Engine::create('Router');
            $user=V_Engine::create('User');
            if (V_User::getGroup()==0) {
            	V_DB::query('DELETE FROM v_work_list WHERE id='.V_DB::escape($router->getId()));
            	V_DB::query('DELETE FROM v_work_list_comments WHERE list_id='.V_DB::escape($router->getId()));
            	V_DB::query('DELETE FROM v_work_list_files WHERE list_id='.V_DB::escape($router->getId()));
            	V_DB::query('DELETE FROM v_work_list_phones WHERE list_id='.V_DB::escape($router->getId()));
            	V_DB::query('DELETE FROM v_work_list_emails WHERE list_id='.V_DB::escape($router->getId()));
            	V_DB::query('DELETE FROM v_work_list_contacts WHERE list_id='.V_DB::escape($router->getId()));
            	V_DB::query('DELETE FROM v_work_list_states WHERE list_id='.V_DB::escape($router->getId()));
            	echo "OK";
            } else {
            	$message='Пользователь '.$user->getLogin().' подал заявку на удаление рабочего листа';
            	if (V_DB::insert('v_job_list',Array(
                	Array ('name' => 'work_user_id','value' => '"-1"'),
                	Array ('name' => 'target_group_id','value' => '"1"'),
                	Array ('name' => 'send_user_id','value' => '"'.V_User::getId().'"'),
                	Array ('name' => 'message','value' => '"'.$message.'"'),
                	Array ('name' => 'target_isget','value' => '"0"')
                ))) echo "DEL";
                else echo "ERROR";
                $job_id=mysql_insert_id();
               	V_DB::insert('v_job_list_items',Array(
                	Array ('name' => 'job_id','value' => '"'.$job_id.'"'),
                	Array ('name' => 'list_id','value' => '"'.V_DB::escape($router->getId()).'"')
                ));
            }
        }
        // ------------------------------------------------------------------------------------------
    	// ----------Импорт csv файла----------------------------------------------------------------
    	// ------------------------------------------------------------------------------------------
        function csv () {
        	$tempfile=$_FILES['csvfile']['tmp_name'];
	    	$filename=rand(10,10000000).".csv";
	    	if (is_uploaded_file ($tempfile)) {
				while (file_exists("upload/temp/$filename")) $filename=rand(10,10000000).".csv";
				if (copy($tempfile,"upload/temp/$filename")) {
					$f = fopen("upload/temp/$filename", "rt") or die("Ошибка!");
					$addcount=0;
                	$errorcount=0;
                	$existcount=0;
					for ($i=0; $data=$this->fgetcsv($f,1000,";"); $i++) {
  							$num = count($data);
							$user = new V_User();
        					V_Engine::load('Check');
                			$state="OK";
                			if (trim($data[0]) == '') {
                    			$state="INPUT";
                			} else {
                    			$result=V_DB::select('v_work_list','client_company_name='.$data[0]);
                    			if (($result) and (V_DB::num_rows ($result) > 0))
                        		$state="EXISTCOMPANY";
                			}
                			if (trim($data[1]) == '') {
                    			$state="INPUT";
                			} else {
                    			$result=V_DB::select('v_work_list_phones','phone='.$data[1]);
                    			if (($result) and (V_DB::num_rows ($result) > 0)) 
                        		$state="EXISTPHONE";
                    			else if (!V_Check::phone($data[1])) $state="PHONEERROR";
                			}
            				if (trim($_POST['csvdate']) == '') {
                    			$state="INPUT";
                			} else {
                    			if (!V_Check::date($_POST['csvdate'])) $state="DATEERROR";
                			}
                			if ($state=="OK") {
                				if (V_DB::insert('v_work_list',Array(
                					Array ('name' => 'user_add_id','value' => '"'.V_User::getId().'"'),
                					Array ('name' => 'user_add_issend','value' => 0),
            						Array ('name' => 'user_work_id','value' => 0),
            						Array ('name' => 'user_work_isget','value' => 0),
                					Array ('name' => 'client_company_name','value' => '"'.$data[0].'"'),
                					Array ('name' => 'client_company_category','value' => '""'),
                					Array ('name' => 'client_city','value' => '""'),
                					Array ('name' => 'client_site','value' => '""'),
            						Array ('name' => 'list_add_date','value' => 'NOW()'),
            						Array ('name' => 'list_quick_add','value' => 1),
            						Array ('name' => 'list_is_sign','value' => 0),
            						Array ('name' => 'client_call_date','value' => '"'.$_POST['csvdate'].'"'),
            						Array ('name' => 'client_state','value' => 0)
                				)) and
                				V_DB::insert('v_work_list_phones',Array(
                					Array ('name' => 'list_id','value' => mysql_insert_id()),
                					Array ('name' => 'phone','value' => '"'.$data[1].'"')
                				))) $addcount++;
                				else $errorcount++;
                			} else {
                				if ($state=="EXISTPHONE" or $state=="EXISTCOMPANY") echo $existcount++;
                				else $errorcount++;
                			}
                			$message='Добавлено листов - '.$addcount.'<br />';
                			$message.='Листов с ошибками - '.$errorcount.'<br />';
                			$message.='Уже существующих листов - '.$existcount.'<br />';
                			echo "<script type='text/javascript'>";
                			echo "window.parent.ShowMessage('".$message."',false)";
		    				echo "</script>";
						}
					fclose($f);
				} else {
		    		echo "ERROR";
				}
	    	}
	    	unlink ("upload/temp/$filename");
        }
        // ------------------------------------------------------------------------------------------
    	// ----------Разбор csv файла------------------------------------------------
    	// ------------------------------------------------------------------------------------------
		function fgetcsv($f, $length, $d=",", $q='"') {
        $list = array();
        $st = fgets($f, $length);
        if ($st === false || $st === null) return $st;
        if (trim($st) === "") return array("");
        while ($st !== "" && $st !== false) {
            if ($st[0] !== $q) {
                # Non-quoted.
                list ($field) = explode($d, $st, 2);
                $st = substr($st, strlen($field)+strlen($d));
            } else {
                # Quoted field.
                $st = substr($st, 1);
                $field = "";
                while (1) {
                    # Find until finishing quote (EXCLUDING) or eol (including)
                    preg_match("/^((?:[^$q]+|$q$q)*)/sx", $st, $p);
                    $part = $p[1];
                    $partlen = strlen($part);
                    $st = substr($st, strlen($p[0]));
                    $field .= str_replace($q.$q, $q, $part);
                    if (strlen($st) && $st[0] === $q) {
                        # Found finishing quote.
                        list ($dummy) = explode($d, $st, 2);
                        $st = substr($st, strlen($dummy)+strlen($d));
                        break;
                    } else {
                        # No finishing quote - newline.
                        $st = fgets($f, $length);
                    }
                }

            }
            $list[] = $field;
        }
        return $list;
    	}
    	// ------------------------------------------------------------------------------------------
    	// ----------Прикрепленные файлы - получение, добавление, удаление---------------------------
    	// ------------------------------------------------------------------------------------------
    	function filelist_get () {
    		$user=V_Engine::create('User');
			V_Engine::load('DB');
			$router=V_Engine::create('Router');
			// Получение файлов листа
            $result=V_DB::query('SELECT file_caption, file_name, id, list_id '.
            					'FROM v_work_list_files '.
            					'WHERE list_id='.$_POST['id']);
            if ($result) {
            	$files = Array();
            	for ($i=0;$i<V_DB::num_rows($result);$i++) {
                    $file=V_DB::fetch_array($result);
                    $files[]=$file['file_caption'].
                    	' <a target="_blank" href="/upload/files/'.$file['file_name'].'">скачать</a>'.
                    	' <span class="button" onclick="filelist.del('.
                    					$file['id'].','.$file['list_id'].')">удалить</span>';
            	}
                $filelist=implode('<br />',$files);
            } 
            if (!$filelist) $filelist="Прикрепленных файлов нет";
            echo $filelist;
    	}
    	function filelist_add () {
        	$tempfile=$_FILES['addfile']['tmp_name'];
        	$listid=$_POST['list_id'];
        	$caption=$_POST['addfilecaption'];
	    	$filename=$listid.'_'.rand(10,10000).'.'.substr(strrchr($_FILES['addfile']['name'], '.'), 1);
	    	if (is_uploaded_file ($tempfile)) {
				while (file_exists("upload/files/$filename")) 
					$filename=$listid.'_'.rand(10,10000).'.'.substr(strrchr($_FILES['addfile']['name'], '.'), 1);
				if (trim($caption)=='') $caption=$filename;
				if (copy($tempfile,"upload/files/$filename")) {
					V_Engine::load('DB');
					if (V_DB::insert('v_work_list_files',Array(
                		Array ('name' => 'list_id','value' => '"'.$listid.'"'),
            			Array ('name' => 'file_name','value' => '"'.$filename.'"'),
            			Array ('name' => 'file_caption','value' => '"'.$caption.'"'),
            			Array ('name' => 'file_type','value' => '"'.$_FILES['addfile']['type'].'"'),
                	))) $message="Файл прикреплен";
                	else $message="Ошибка сохранения. Попробуйте еще раз";
				}else $message="Ошибка загрузки. Попробуйте еще раз";
				echo "<script type='text/javascript'>";
                echo "window.parent.ShowMessage('".$message."',false);";
                echo "window.parent.filelist.add_hide();";
                echo "window.parent.filelist.get();";
		    	echo "</script>";
	    	}	
        }
		function filelist_delete () {
        	V_Engine::load('DB');
        	$user=V_Engine::create('User');
        	if (V_User::getGroup()==0) {
        		$fileid=$_POST['fileid'];
				// Получение файлов листа
				$result=V_DB::query('SELECT file_name FROM v_work_list_files '.
            						'WHERE id='.$_POST['fileid']);
				if ($result) $file=V_DB::fetch_array($result);
            	if (V_DB::query('DELETE FROM v_work_list_files WHERE id='.$fileid))	{
            		echo "OK";
            		unlink ("upload/files/$file[file_name]");
            	}
        	}
        }
}